# -*- coding: UTF-8 -*-

__author__ = 'zhangpengju'

import requests
import base64
import json


class FaceDetect():
    '''\
    二个参数：
    detect_url:检测用的url,用BdFaceDetectionGetAccessToken().face_detection_url()来提取
    
    img_path:图片地址
    属性：
    self.base64_image(img_path):把图片转成base64编码格式
    self.result:返回图处检测结果
    如下：
    {
    'error_code': 0,
    'error_msg': 'SUCCESS',
    'log_id': 1589897545659, 'timestamp': 1532439795,
    'cached': 0,
    'result': {
              'face_num': 1,
              'face_list': [
                            {
                            'face_token': '9ca38cad6aa552b16595cf80432ab8f3',
                            'location': {'left': 494.2722778,
                                        'top': 767.2266846,
                                        'width': 541,
                                        'height': 532,
                                        'rotation': -91},
                            'face_probability': 1,
                            'angle': {'yaw': 2.255952358,
                                      'pitch': 0.441129595,
                                      'roll': -91.31650543},
                                      
                            'face_shape': {'type': 'round', 'probability': 0.4173637331},
                            'face_type': {'type': 'human','probability': 0.9992184639}
                            }
                            ]
                }
    }
    '''
    headers = {'Content-Type': 'application/json; charset=UTF-8'}  #要以此为请求头headers

    def __init__(self,detect_url,img_path):

        self.detect_url = detect_url
        self.img_path = img_path
        self.result = self.result()

    def base64_image(self,img_path):
		
        with open(self.img_path,'rb') as f:
            base64_data = base64.b64encode(f.read())

        return str(base64_data,'utf-8')
		
    def result(self):
		
        params = {
            "image":self.base64_image(self.img_path),
            "image_type":"BASE64",
            "face_field":"faceshape,facetype",

                }
        data = json.dumps(params)
        response = requests.post(self.detect_url,data = data,headers = self.headers)
        result = response.json()
        return result


if __name__ == "__main__":
    from bd_ai_token import BdFaceDetectionGetAccessToken as BFGAT
    face_detection_url =BFGAT().face_detection_url()
    img_path =r'C:\Users\Administrator\Desktop\新建文件夹\img\20180720181429.jpg'
    now = FaceDetect(face_detection_url,img_path).result
    print(now)


